<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class ExpressShipment_m extends CI_Model {
	function __construct()
    {
        parent::__construct();
    }

	function saveexpress()
	{
	    $postdata="";
		//YT 云途   YW 燕文
        $express_type=array('UPS'=>2,'DHL'=>3,'CNE'=>4,'UBI'=>5,'YT'=>6,'YW'=>7,'EMS'=>8,'YIDA'=>10,'JIAC'=>12,'ZTO'=>14);
		$orderlist = trim($this->input->post('orderlist'));
		if(!$orderlist)
		{
			$this->fun->phpalert(2, "请输入订单号");
			die;
		}
        $post_express_type=$this->input->post('type');
        $orderType=$express_type[$post_express_type];
		$orderlist = substr($orderlist,0,-1);
		$orderdata = implode("','",explode(",",$orderlist));	//替换字符
		$data = $this->db->get_where("db_order_list","order_sn in ('".$orderdata."')")->result_array();
        //echo  $this->db->last_query();
	    $insert_data=array();//存储已经正确的需要做交运的mabang订单id
		if(count($data)>0){
			foreach($data as $key=>$rs){
			     $insert_ids=array();
			     $insert_ids['order_id']=$rs['order_id'];
                 $insert_ids['order_sn']=$rs['order_sn'];
		
				$rsdb = $this->db->get_one("SELECT * FROM db_mabangorder WHERE orderID='".trim($rs["order_sn"])."' AND orderType ='".$orderType."'");
				$deliver_arr=array('DHL'=>'DHL','CNE'=>"CNE",'UBI'=>"UBI澳洲",'YIDA'=>'日本邮政','JIAC'=>'佳成物流','ZTO'=>'中通快递');
                if($rsdb)
				{
					$thi1orderid = $rsdb["id"];
				}else{
					$thi1orderid = 0;
				}

					if( $rs["tel"]=='' &&  $rs["mobile"] =='null')
					{
						$rs["tel"] = '00000000';
					}
					
					switch ($rs["order_status"]) {
						case 1;
							$statustext = '新订单';
							break;
						case 2:
							$statustext  = '已支付';
							break;
						case 3:
							$statustext  = '配货中';
							break;
						case 4:
							$statustext  = '已发货';
							break;
						case 5:
							$statustext  = '已完成';
							break;
						case 6:
							$statustext  = '已作废';
							break;
						case 7:
							$statustext  = '待审查';
							break;
				  }
                    $postdata['deliver']=$deliver_arr[$post_express_type];
                    $cnetype=$this->input->post('cnetype');
                    $jiactype=$this->input->post('jiactype');
                    if(!empty($cnetype) && $orderType==4){
                        $postdata['deliver']=$cnetype; //   
                    }
                    if(!empty($jiactype) && $orderType==12){
                        $postdata['deliver']=$jiactype; //   
                    }
                    
					$postdata["orderType"] = $orderType;
					$postdata["orderID"] = trim($rs["order_sn"]);
					$postdata["statusst"]=$statustext;
					$postdata["customerid"] = addslashes($rs["consignee"]);
					$postdata["customertype"]= $rs["shopname"];
					$postdata["customertel1"]= $rs["tel"]?$rs["tel"]:$rs["mobile"];
					$postdata["customertel2"]= $rs["mobile"];
					//获取国家标识strtoupper
					$rscountry = $this->fun->getdatabasesdetail("d_country"," AND countrynamecn='".strtoupper(trim($rs["country"]))."'");
					if($rscountry)
					{
						$customerqq = $rscountry["countryid"];
                         $rs["country_code"]= $rs["country_code"]==""?$customerqq:$rs["country_code"];
					}
					$postdata["customerqq"]=  $rs["country_code"];	//国家标识
					$postdata["customercountry"]= $rs["country"];//国家
					$postdata["customerprovince"]= $rs["province"];
					$postdata["customercity"]= $rs["city"];
					$postdata["customeraddress"]= $rs["address"].$rs["address2"];
					$postdata["customerzipcode"]= $rs["zipcode"];
					$postdata["moneytype"]= $rs["moneytype"];
					$postdata["content1"]= NULL;
					$postdata["intime"]= date("Y-m-d H:i:s");
					$postdata["createUser"]=$_COOKIE["username"];
				
					if( $thi1orderid)
					{
						$postdata["isexe"]= 0;
						$postdata["exememo"]='重复提交订单';
						$this->db->update('db_mabangorder', $postdata, 'id=' . $thi1orderid);
                        $insert_ids['mabang_id']= $mabang_id=$thi1orderid;
                       
					}else{

						 $res = $this->db->query($this->db->insert_string('db_mabangorder', $postdata));
                         $insert_ids['mabang_id']=$mabang_id=$this->db->insert_id();
                        
					}

					//DHL使用远程交运功能
					if($this->config->item('isdhlremote')==1 && $orderType==3)
					{
                        if(stripos($postdata["customeraddress"],'PO Box')===0 or strlen($postdata['customerid'])<=3){//have error
                            if(strlen($postdata['customerid'])<=3){
                    			$exememo = "收件人名称太过简短";
                            }else{
                    			$exememo = "收货地址PO Box位置不够具体";
                            }
                			$updateinfo["isexe"] = 2;
                    		$updateinfo["exememo"] = $exememo;
                    		$updateinfo["mailinstime"] =time();
                    		$this->db->query($this->db->update_string('db_mabangorder', $updateinfo, 'id=' .$mabang_id));
                        }else{
                            //保存数据待远程交运
    						$this->load->library('Expresssend');
    						$this->expresssend->saveremotedata($postdata,$mabang_id);     
                        }
					}

					
                   // echo  $this->db->last_query();
               // $insert_ids['mabanginfo']=$rsdb;
               // $insert_ids['orderinfo']=$rs;
                $insert_data[]=$insert_ids;
			}
		}	
		return $insert_data;
	}


	function getSearchCountry()
	{

		$depts = $this->fun->getdatabaseslist("d_chinaexpress"," and `OPENFLAG` IS not NULL","id,NAME,FILED1,FILED3,FILED4","group by FILED1");
        foreach ($depts as $key => $rs) {
            $deptsname[$rs["FILED3"]][] = $rs;
        }
	
		return $deptsname;
	}

	function selectShop()
	{
		$depts = $this->fun->getdatabaseslist("d_shop"," and del_flag =0","id,name,platfromname");
        foreach ($depts as $key => $rs) {
            $deptsname[$rs["platfromname"]][] = $rs;
        }
		return $deptsname;
	}
	function saveexpresstype()
	{
		$postdata= "";
		$postdata["name"]    = trim($this->input->post('name'));
		$postdata["aliexpress_express"] = trim($this->input->post('aliexpress_express'));
		$postdata["ebay_express"] = trim($this->input->post('ebay_express'));
		$postdata["amazon_express"] = trim($this->input->post('amazon_express'));
		$postdata["wish_express"] = trim($this->input->post('wish_express'));
		$postdata["magento_express"] = trim($this->input->post('magento_express'));
		$postdata["weburl"] = trim($this->input->post('weburl'));
		$postdata["address"] = trim($this->input->post('address'));
		$postdata["opertime"] = date("Y-m-d H:i:s");
		$postdata["oper"] = $_COOKIE["username"];
		
		if($this->input->post("id"))
		{
			$this->db->update("db_order_express",$postdata,"id=".$this->input->post("id"));
			$intid =intval($this->input->post("id"));
		}else{
			$this->db->insert("db_order_express",$postdata);
			$intid = $this->db->insert_id();
		}

		return true;
	}

	function saveordersearch()
	{
		if($this->input->post('orderstatus'))
		{
			$orderstatus  =implode(",",$this->input->post('orderstatus'));
		}
		$postdata= "";
		$postdata["name"]    = trim($this->input->post('name'));
		$postdata["country"] = trim($this->input->post('country'));
		$postdata["countryflag"] = trim($this->input->post('countryflag'));
		$postdata["shopname"] = trim($this->input->post('shopname'));
		$postdata["shopflag"] = trim($this->input->post('shopflag'));
		$postdata["goodsnoflag"] = trim($this->input->post('goodsnoflag'));
		$postdata["goodsno"] = trim($this->input->post('goodsno'));
		$postdata["weight1"] = trim($this->input->post('weight1'));
		$postdata["weight2"] = trim($this->input->post('weight2'));
		$postdata["amount1"] = trim($this->input->post('amount1'));
		$postdata["amount2"] = trim($this->input->post('amount2'));
		$postdata["freight1"] = trim($this->input->post('freight1'));
		$postdata["freight2"] = trim($this->input->post('freight2'));
		$postdata["orderstatus"] = $orderstatus;
		$postdata["ordertime"] = trim($this->input->post('ordertime'));
		$postdata["logisticsID"] = intval($this->input->post('logisticsID'));
		$rsdb = $this->fun->getdatabasesdetail("db_order_express"," AND id=".intval($this->input->post('logisticsID')));
		$postdata["logistics"] = $rsdb["name"];
		$postdata["priority"] = trim($this->input->post('filed13'));
		$postdata["weightflag"] = trim($this->input->post('weightflag'));
		$postdata["amountflag"] = trim($this->input->post('amountflag'));
		$postdata["freightflag"] = trim($this->input->post('freightflag'));
		$postdata["ordermoneyflag"] = trim($this->input->post('ordermoneyflag'));
		$postdata["opertime"] = date("Y-m-d H:i:s");
		$postdata["oper"] = $_COOKIE["username"];
		
		$this->db->trans_begin();
		
			if($this->input->post("id"))
			{
				$this->db->update("db_order_search",$postdata,"id=".$this->input->post("id"));
			    $intid =intval($this->input->post("id"));
			}else{
				$this->db->insert("db_order_search",$postdata);
			    $intid = $this->db->insert_id();
			}
			
			$sql = "";
			if($postdata["country"])	//国家Sql
			{
				$country = explode(";",$postdata["country"]);
				$country = implode("','",$country );
				if($this->input->post("countryflag")==1)
					$sql.= " AND country_cn not in ('".$country."')";
				else
					$sql.= " AND country_cn in ('".$country."')";
			}
			if($postdata["shopname"])	//店铺SQL
			{
				$shopname = explode(";",$postdata["shopname"]);
				$shopname = implode("','",$shopname );

				//$shopid = $this->fun->getdatabasesdetail("d_shop"," AND shopname in ('".$shopname."')"," GROUP_CONCAT(id) as shopid");
				//print_r($shopid);
				//die;
				if($this->input->post("shopflag")==1)
					$sql.= " AND shopname not in ('".$shopname."')";
				else
					$sql.= " AND shopname in ('".$shopname."')";
			}

			if($postdata["goodsno"])	//商品编号SQL
			{
				$goodsno = explode(";",$postdata["goodsno"]);
				$goodsno = implode("','",$goodsno );
				if($this->input->post("goodsnoflag")==1)
					$sql.= " and order_id in(select distinct order_id from db_order_sell where goods_sn not in ('".$goodsno."'))";
				else
					$sql.= " and order_id in(select distinct order_id from db_order_sell where goods_sn  in ('".$goodsno."'))";
			}
			
			if($postdata["weight2"])	//包裹重量
			{
				if($postdata["weightflag"] ==1)
				{
					$sql.= " AND orderweight not between $postdata[weight1] and $postdata[weight2] ";
				}else{
					$sql.= " AND orderweight between $postdata[weight1] and $postdata[weight2] ";
				}
			}

			
			if($postdata["amount2"])	//金额SQL
			{
				if($postdata["amountflag"] ==1)
				{
					if($postdata["ordermoneyflag"] ==1)
					{
						$sql.= " AND goods_amount+shipping_fee not between $postdata[amount1] and $postdata[amount2] ";
					}else{
						$sql.= " AND goods_amount not between $postdata[amount1] and $postdata[amount2] ";
					}
				}else{
					if($postdata["ordermoneyflag"] ==1)
					{
						$sql.= " AND goods_amount+shipping_fee between $postdata[amount1] and $postdata[amount2] ";
					}else{
						$sql.= " AND goods_amount between $postdata[amount1] and $postdata[amount2] ";
					}
					
				}
			}
			if( $postdata["freight2"])	//运费SQL
			{
				if($postdata["freightflag"] ==1)
				{
					$sql.= " AND shipping_fee not between $postdata[freight1] and $postdata[freight2] ";
				}else{
					$sql.= " AND shipping_fee between $postdata[freight1] and $postdata[freight2] ";
				}
				
			}
			
			if($orderstatus)	//订单状态SQL
			{
				$sql.= " and order_status in($orderstatus)";
			}
			if($postdata["ordertime"])	//订单时间SQL
			{
					$daynum = $postdata["ordertime"];
					$time = strtotime("-$daynum day");
					$sql.= " and ordertime > date_add(now(), INTERVAL -$daynum day)";
			}
			if($sql)
			{
				$this->db->update("db_order_search",array("sqlfilter"=>$sql),"id=".$intid);
			}
			
			if ($this->db->trans_status() === FALSE)
			{
				$this->db->trans_rollback();
				return false;
			}
			else
			{
				$this->db->trans_commit();
			}
		
		return true;
	}
	
}
